package top.techqi.app.wol

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.widget.PopupMenu
import androidx.core.net.toUri
import androidx.fragment.app.activityViewModels
import androidx.navigation.fragment.findNavController
import androidx.recyclerview.widget.ItemTouchHelper
import androidx.recyclerview.widget.RecyclerView
import top.techqi.app.wol.databinding.FragmentListBinding
import top.techqi.app.wol.databinding.ItemDeviceBinding
import top.techqi.app.wol.utils.ImageUtils
import top.techqi.base.BaseFragment
import top.techqi.base.util.toast
import top.techqi.view.recyclerview.tile.BindHolder
import top.techqi.view.recyclerview.tile.TileAdapter
import top.techqi.view.recyclerview.tile.TilePortion
import top.techqi.view.recyclerview.tile.TileRecord


class ListFragment : BaseFragment<FragmentListBinding>(FragmentListBinding::inflate),
    DevicePortion.Listen {
    private val mainViewModel by activityViewModels<MainViewModel>()

    private val adapter = TileAdapter().also {
        it.register(DevicePortion(this))
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mainViewModel.refreshDevice()
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        binding.rccRecycler.adapter = adapter

        mainViewModel.devices.observe(viewLifecycleOwner) { list ->
            val n = list.map { item ->
                DevicePortion.Record(item.id, item.icon, item.name, item.addr)
            }
            adapter.commit(n)
        }
    }

    override fun onClick(addr: String) {
        mainViewModel.x(addr)
        toast(R.string.main_list_tips_turn)
    }

    override fun onEdit(deviceId: Int) {
        // 导航到编辑页面，传递设备ID
        val bundle = Bundle().apply {
            putInt("deviceId", deviceId)
        }
        findNavController().navigate(R.id.action_FirstFragment_to_SecondFragment, bundle)
    }

    override fun onDelete(deviceId: Int) {
        AlertDialog.Builder(requireContext())
            .setTitle("确认删除")
            .setMessage("确定要删除这个设备吗？")
            .setPositiveButton("删除") { _, _ ->
                mainViewModel.removeDevice(deviceId)
                toast("设备已删除")
            }
            .setNegativeButton("取消", null)
            .show()
    }
}

class DevicePortion(private val l: Listen) :
    TilePortion<DevicePortion.Holder, DevicePortion.Record>() {
    override fun onMakeHolder(inflater: LayoutInflater, container: ViewGroup): Holder {
        val holder = Holder(inflater, container)
        holder.binding.root.setOnClickListener {
            holder.record?.addr?.let { l.onClick(it) }
        }
        holder.binding.root.setOnLongClickListener {
            val menu = PopupMenu(it.context, it)
            menu.inflate(R.menu.menu_main_list)
            menu.setOnMenuItemClickListener { item ->
                when (item.itemId) {
                    R.id.menu_edit -> {
                        holder.record?.let { record ->
                            l.onEdit(record.index)
                        }
                        true
                    }
                    R.id.menu_delete -> {
                        holder.record?.let { record ->
                            l.onDelete(record.index)
                        }
                        true
                    }
                    else -> false
                }
            }
            menu.show()
            return@setOnLongClickListener true
        }
        return holder
    }

    override fun onBindRecord(holder: Holder, record: Record) {
        // 优先从本地路径加载图片
        if (!record.icon.isNullOrEmpty()) {
            val bitmap = ImageUtils.loadImageFromLocal(record.icon)
            if (bitmap != null) {
                holder.binding.imgIcon.setImageBitmap(bitmap)
            } else {
                // 如果本地图片不存在，尝试从Uri加载
                holder.binding.imgIcon.setImageURI(record.icon.toUri())
            }
        } else {
            holder.binding.imgIcon.setImageResource(android.R.drawable.ic_menu_gallery)
        }
        holder.binding.txtName.text = record.name
        holder.binding.txtAddr.text = record.addr
    }

    data class Record(
        override val index: Int,
        val icon: String?,
        val name: String,
        val addr: String,
    ) : TileRecord

    class Holder(inflater: LayoutInflater, container: ViewGroup) :
        BindHolder<Record, ItemDeviceBinding>(inflater, container, ItemDeviceBinding::inflate)

    interface Listen {
        fun onClick(addr: String)
        fun onEdit(deviceId: Int)
        fun onDelete(deviceId: Int)
    }
}